package com.techysky.repository.factory;

import java.io.Serializable;
import javax.persistence.EntityManager;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import com.techysky.repository.impl.CoreRepositoryImpl;

/**
 * * * @author zhangxu * @date 2016年11月11日 上午9:36:49 * @remark 公用持久层工厂 * @param
 * <R> * @param <T> * @param <I>
 */
public class CoreRepositoryFactory<R extends JpaRepository<T, I>, T, I extends Serializable>
		extends JpaRepositoryFactoryBean<R, T, I> {
	@Override
	protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
		return new CustomRepositoryFactory<T, I>(em);
	}

	private static class CustomRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
		private final EntityManager em;

		public CustomRepositoryFactory(EntityManager em) {
			super(em);
			this.em = em;
		}

		@SuppressWarnings({ "unchecked", "unused" })
		protected Object getTargetRepository(RepositoryMetadata metadata) {
			return new CoreRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), em);
		}

		@Override
		protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
			return CoreRepositoryImpl.class;
		}
	}
}